/**
 * @file service.h
 * @author HaoyuWang (136046355@qq.com)
 * @brief 服务类
 * @version 0.1
 * @date 2025-01-24
 * 
 * @copyright Copyright (c) 2025
 * 
 */

#ifndef __SERVICE_H__
#define __SERVICE_H__

#include "lua.hpp"

#include <cstdint>
#include <memory>
#include <string>
#include <queue>
#include <unordered_map>

#include "base_msg.h"
#include "service_msg.h"
#include "socket_msg.h"
#include "conn_writer.h"
#include "packet_base.h"
#include "log_msg.h"


class Service
{
private:
    std::shared_ptr<BaseMsg> PopMsg();
public:
    Service();
    virtual ~Service();

    virtual void OnInit();
    virtual void OnMsg(std::shared_ptr<BaseMsg> msg);
    virtual void OnExit();
    void PushMsg(std::shared_ptr<BaseMsg> msg);
    bool ProcessMsg();
    void ProcessMsgs(int max);

    void OnServiceMsg(std::shared_ptr<ServiceMsg> msg);
    void OnRWMsg(std::shared_ptr<SocketRWMsg> msg);
    void OnLogMsg(std::shared_ptr<LogMsg> msg);

    virtual void OnAcceptMsg(std::shared_ptr<SocketAcceptMsg> msg);
    virtual void OnSocketData(int fd, const char* buff, int len);
    virtual void OnSocketWritable(int fd);
    virtual void OnSocketClose(int fd);
    virtual void OnPacketRead(int fd, PacketBase& packet);

    inline void SetID(uint32_t id){
        id_ = id;
    }
    inline uint32_t GetID(){
        return id_;
    }

    inline void SetType(std::shared_ptr<std::string> type){
        type_ = type;
    }
    inline std::shared_ptr<std::string> GetType(){
        return type_;
    }

    inline void SetExiting(bool exiting){
        exiting_ = exiting;
    }
    inline bool IsExiting(){
        return exiting_;
    }

    void SetInGlobal(bool in_global);
    inline bool IsInGlobal(){
        return in_global_;
    }

public:
    uint32_t id_;
    std::shared_ptr<std::string> type_;
    bool exiting_ = false;

    std::queue<std::shared_ptr<BaseMsg>> msg_queue_;
    pthread_spinlock_t queue_lock_;

    bool in_global_;
    pthread_spinlock_t in_global_lock_;

    lua_State* lua_state_;
};


#endif  // __SERVICE_H__